package com.bobi.tfca.ui.mainnavigation.message.chatroom

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.navigation.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.databinding.FragmentGroupDetailBinding
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.MessageAPI
import com.bobi.tfca.network.client.AppCache
import com.bobi.tfca.ui.adapter.GroupMemberHeadAdapter
import com.bobi.tfca.util.LogUtil
import com.bobi.tfca.util.RealPathUtil
import com.bumptech.glide.Glide
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

class GroupDetailFragment : BaseFragment<FragmentGroupDetailBinding, GroupDetailFragmentVM>(
    FragmentGroupDetailBinding::inflate,
    GroupDetailFragmentVM::class.java,
    true
) {
    // memberRV
    private lateinit var memberRV: RecyclerView
    private lateinit var imagePickerLauncher: ActivityResultLauncher<Intent>
    private lateinit var imageView: ImageView
    private lateinit var groupNameTV: TextView
    private lateinit var groupNumTV: TextView

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private val REQUIRED_PERMISSIONS = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE
    )

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            if (permissions.all { it.value }) {
                // 如果所请求的所有权限都被授予，则执行相应的操作，比如打开相册
            } else {
                // 如果有任何一个权限被拒绝，则可以向用户解释为什么需要这些权限，并提供一个再次请求的机会
                Toast.makeText(requireActivity(), "选择图片需要权限", Toast.LENGTH_SHORT).show()
            }
        }


    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun checkPermissions(): Boolean {
        val isAllGranted = REQUIRED_PERMISSIONS.all {
            ContextCompat.checkSelfPermission(
                requireContext(),
                it
            ) == PackageManager.PERMISSION_GRANTED
        }
        // 如果权限没有授予，请求权限
        if (!isAllGranted) {
            requestPermissionLauncher.launch(REQUIRED_PERMISSIONS)
            return false
        } else {
            return true
        }
    }

    // 在适当的时候调用请求权限的方法
    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun openPictureChooser() {
        if (checkPermissions()) {
            // 如果权限已被授予，则执行相应的操作，比如打开相册
            // 点击图片后，更改图片
            // 打开图片选择器
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            imagePickerLauncher.launch(intent)
        }
    }


    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentGroupDetailBinding,
        viewModel: GroupDetailFragmentVM?,
        savedInstanceState: Bundle?
    ) {
        val groupId = publicViewModel!!.chatRoom.value!!.groupId
        imageView = binding.ivGroupPicture
        groupNameTV = binding.tvGroupName
        groupNumTV = binding.viewMembers

        // 设置头部菜单的按钮
        setTopPanelStyle(binding)

        // 初始化RecyclerView
        initRecyclerView(binding)

        // 设置会员小图监听
        viewModel!!.headMembers.observe(this@GroupDetailFragment) {
            val adapter = memberRV.adapter as GroupMemberHeadAdapter
            adapter.memberResponseList = it
            adapter.notifyDataSetChanged()
        }

        // 设置查看全部群成员监听
        binding.toMemberList.setOnClickListener {
            requireActivity().findNavController(R.id.app_nav)
                .navigate(R.id.action_groupDetailFragment_to_memberListFragment)
        }

        // 设置修改群名称监听
        binding.toEditGroupName.setOnClickListener {
            // 如果是群主，才能点击
            if (checkGroupRole()) {
                requireActivity().findNavController(R.id.app_nav)
                    .navigate(R.id.action_groupDetailFragment_to_editGroupNameFragment)
            } else {
                Toast.makeText(requireActivity(), "请联系群主操作", Toast.LENGTH_SHORT).show()
            }
        }
        // 设置添加群员监听
        binding.llAddMember.setOnClickListener {
            // 如果是群主，才能点击
            if (checkGroupRole()) {
                requireActivity().findNavController(R.id.app_nav)
                    .navigate(R.id.action_groupDetailFragment_to_groupAddMemberFragment)
            } else {
                Toast.makeText(requireActivity(), "请联系群主操作", Toast.LENGTH_SHORT).show()
            }
        }
        // 设置移除群员监听
        binding.llRemoveMember.setOnClickListener {
            // 如果是群主，才能点击
            if (checkGroupRole()) {
                requireActivity().findNavController(R.id.app_nav)
                    .navigate(R.id.action_groupDetailFragment_to_memberRemoveFragment)
            } else {
                Toast.makeText(requireActivity(), "请联系群主操作", Toast.LENGTH_SHORT).show()
            }
        }
        // 设置解散群员监听和修改头像
        if (checkGroupRole()) {
            binding.btGroupDisband.visibility = View.VISIBLE
            binding.btGroupDisband.setOnClickListener {
                // 创建确认框
                val builder = AlertDialog.Builder(requireContext())
                builder.setTitle("解散群聊")
                builder.setMessage("你确认解散群聊吗")

                // 设置确认按钮和点击事件
                builder.setPositiveButton("确认") { dialog, which ->
                    viewModel.disbandGroup(groupId, publicViewModel!!, this)
                }

                // 设置取消按钮和点击事件
                builder.setNegativeButton("取消") { dialog, which ->
                }

                // 创建并显示确认框
                val dialog: AlertDialog = builder.create()
                dialog.show()
            }

            binding.ivEditGroupHead.visibility = View.VISIBLE
            binding.ivEditGroupHead.setOnClickListener{
                uploadImage()
            }
        }

        registerImagePickerResult()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        // 设置viewmodel监听
        publicViewModel!!.apply {
            chatRoom.observe(viewLifecycleOwner) {
                val url = it.groupHead
                if (url != null && url.isNotBlank() && (!"null".equals(url))) {
                    Glide.with(this@GroupDetailFragment).load(url).placeholder(R.mipmap.default_avatar).into(imageView)
                }
                groupNameTV.text = it.groupName
                groupNumTV.text = "查看全部" + it.groupNum + "位成员"
            }
        }
    }

    private fun registerImagePickerResult() {
        imagePickerLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    val selectedImageUri: Uri? = result.data?.data
                    selectedImageUri?.let {
                        val file = getFileFromUri(selectedImageUri)
                        val requestFile = RequestBody.create(MediaType.parse("image/*"), file)
                        val body =
                            MultipartBody.Part.createFormData("file", file!!.name, requestFile)
                        if (body != null) {
                            LogUtil.i("选择了图片")
                            // 将图片上传至服务器，由服务器上传至腾讯云，将返回的地址设为图片地址。
                            uploadImageToServer(
                                body
                            )
                        } else {
                            LogUtil.i("图片未选择")
                        }
                    }
                }
            }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun uploadImage() {
        openPictureChooser()
    }

    private fun checkGroupRole(): Boolean {
        val ownerId = publicViewModel!!.chatRoom.value!!.ownerId    // 群主id
        val userId = AppCache.getMyInfo().memberId      // 自己的id
        return ownerId == userId
    }

    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(binding: FragmentGroupDetailBinding) {
        val topPanel = binding.topPanel
        val leftLayout = topPanel.leftLayout
        leftLayout.setOnClickListener {
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }
        val rightLayout = topPanel.rightLayout
        rightLayout.visibility = View.GONE
        val title = topPanel.titleText
        // 动态群聊名称
        title.text = "群聊信息"
    }

    /**
     * 初始化RV
     */
    private fun initRecyclerView(binding: FragmentGroupDetailBinding) {
        memberRV = binding.rvGroupMembers
        // 设置布局排列方式，默认垂直排列
        val gridLayoutManager = GridLayoutManager(binding.root.context, 4)
        gridLayoutManager.orientation = LinearLayoutManager.VERTICAL
        memberRV.layoutManager = gridLayoutManager
        // 绑定adapter
        val memberAdapter = GroupMemberHeadAdapter(this, arrayListOf())
        memberRV.adapter = memberAdapter
    }

    private fun getFileFromUri(uri: Uri): File? {
        val filePath = RealPathUtil.getRealPath(requireActivity(), uri)
        return if (filePath != null) File(filePath) else null
    }

    /**
     * 将图片上传至服务器，由服务器上传至腾讯云，将返回的地址设为图片地址。
     */
    private fun uploadImageToServer(
        file: MultipartBody.Part
    ) {
        val groupId = publicViewModel!!.chatRoom.value!!.groupId
        publicViewModel!!.apply {
            request(MessageAPI::class.java).changeGroupHead(groupId, file).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")

                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val result = it.data
                                if (result?.code == 200) {
                                    LogUtil.i("上传成功")
                                    val url = result.data ?: ""
                                    if (url.isNotBlank() && (!"null".equals(url))) {
                                        if (this@GroupDetailFragment.isAdded() && !this@GroupDetailFragment.isDetached()) {
                                            // Fragment还活着
                                            Glide.with(this@GroupDetailFragment).load(url)
                                                .placeholder(R.drawable.default_avatar)
                                                .into(imageView)
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    override fun resumeFragment(viewModel: GroupDetailFragmentVM?) {
        super.resumeFragment(viewModel)
        viewModel!!.getGroupMemberHeadList(publicViewModel!!, this)
    }
}